package com.example.springboot_shopsystem01.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot_shopsystem01.dao.StaffDao;
import com.example.springboot_shopsystem01.domain.Staff;
import com.example.springboot_shopsystem01.service.StaffService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StaffServiceImpl implements StaffService {

    @Autowired
    private StaffDao staffDao;

    @Override
    public Boolean save(Staff staff) {
        return staffDao.insert(staff) > 0;  //返回的数为受影响的行数，大于零就成功
    }

    @Override
    public Boolean update(Staff staff) {
        return staffDao.updateById(staff) > 0;
    }

    @Override
    public Boolean delete(Integer id) {
        return staffDao.deleteById(id) > 0;
    }

    @Override
    public Staff getById(Integer id) {
        return staffDao.selectById(id);
    }

    @Override
    public List<Staff> getAll() {
        return staffDao.selectList(null);
    }

    @Override
    public IPage<Staff> getPage(int currentPage, int pageSize) {  //旧
        IPage page = new Page(currentPage, pageSize);
        staffDao.selectPage(page, null);
        return page;
    }

    @Override
    public IPage<Staff> getPage(int currentPage, int pageSize, Staff staff) {  //可实现条件查询
        //增加条件查询
        LambdaQueryWrapper<Staff> lqw = new LambdaQueryWrapper<Staff>();
        lqw.like(Strings.isNotEmpty(staff.getName()), Staff::getName, staff.getName());
        lqw.like(Strings.isNotEmpty(staff.getLevel()), Staff::getLevel, staff.getLevel());
        lqw.like(Strings.isNotEmpty(staff.getTelephone()), Staff::getTelephone, staff.getTelephone());
        lqw.like(staff.getId() != null, Staff::getId, staff.getId());

        //添加到page中
        IPage page = new Page(currentPage, pageSize); //页数 当前页中数据量
        staffDao.selectPage(page, lqw);  //page为查询的页 lqw为查找的条件
        return page;
    }

    @Override
    public Staff login(Staff staff) {
        // QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper) 的父类
        // 用于生成 sql 的 where 条件, entity 属性也用于生成 sql 的 where 条件

        QueryWrapper<Staff> wrapper = new QueryWrapper<>();// 构建一个查询的wrapper
        wrapper.eq("id", staff.getId())
                .eq("password", staff.getPassword());// 根据包装的条件进行查询，默认为and操作
                //.select("id","name")  这里可以指定搜索得到的字段，其余字段全为null

        return staffDao.selectOne(wrapper);
    }
}
